package com.ruoyi.warning.service.impl;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsRequest;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponse;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponseBody;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dyvmsapi20170525.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.warning.domain.dto.ConfigurationDTO;
import com.ruoyi.warning.domain.entity.Contacts;
import com.ruoyi.warning.domain.entity.Event;
import com.ruoyi.warning.domain.entity.Message;
import com.ruoyi.warning.service.IMessageService;
import com.ruoyi.warning.service.WarningSendService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import static com.ruoyi.common.enums.WarningSendStatus.*;

/**
 * <p>
 * 告警发送的服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-02-06
 */
@Service
public class WarningSendServiceImpl implements WarningSendService {

    @Resource
    private IMessageService messageService;
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Override
    //短信发送服务
    public void sendSms(ConfigurationDTO configurationDTO) throws Exception {
        List<SysDictData> dictList = sysDictDataMapper.selectDictDataByType("sms_setting")   ;
        Map<String, String> resultMap = dictList.stream()
                .collect(Collectors.toMap(
                        item -> item.getDictLabel(),
                        item -> item.getDictValue()
                ));
        // 获取电话号码数组
        String[] phoneArray = configurationDTO.getContacts().stream()
                .map(Contacts::getPhoneNumber)
                .toArray(String[]::new);
        com.aliyun.dysmsapi20170525.Client client = smsCreateClient();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(String.join(",", phoneArray))
                .setSignName(resultMap.get("signName"))
                .setTemplateCode(resultMap.get("templateCode"))
                .setTemplateParam("{\"device\":\""+configurationDTO.getDeviceName()+"\",\"title\":\""+configurationDTO.getTitle()+"\"}");
        // 1.发送短信
        SendSmsResponse sendResp = client.sendSms (sendSmsRequest);
        if (!com.aliyun.teautil.Common.equalString(sendResp.body.code, "OK")) {
            System.out.println("错误信息: " + sendResp.body.message + "");
            return ;
        }
        String bizId = sendResp.body.bizId;
        // 2. 等待 20 秒后查询结果
        Integer maxRetries = 3;//最大查询次数
        Integer sleepTime = 20000;//每次查询间隔时间
        List<Message> list = new java.util.ArrayList<>();
        Integer successCount = 0;
        for(int r = 0;r<maxRetries;r++){
            if(successCount==configurationDTO.getContacts().size()){
                break;
            }
            com.aliyun.teautil.Common.sleep(sleepTime);
            Message message = new Message();
            // 3.查询结果
            for(int i = 0 ;i<configurationDTO.getContacts().size();i++){
                if(r==0){
                    Message newMessage = new Message();
                    newMessage.setDeviceName(configurationDTO.getDeviceName());
                    newMessage.setAreaId(configurationDTO.getAreaId());
                    newMessage.setAreaName(configurationDTO.getAreaName());
                    newMessage.setWarningType(configurationDTO.getWarningType());
                    newMessage.setWarningWay(3);
                    newMessage.setWarningLevel(configurationDTO.getWarningLevel());
                    newMessage.setWarningContact(configurationDTO.getContacts().get(i).getContactsName());
                    newMessage.setWarningContent(configurationDTO.getDeviceName()+" 告警:"+configurationDTO.getTitle());
                    newMessage.setEventId(configurationDTO.getEventId());
                    newMessage.setEventDetailId(configurationDTO.getEventDetailId());
                    list.add(newMessage);
                }
                message = list.get(i);
                if(ObjectUtils.isEmpty(message.getWarningStatus())||message.getWarningStatus()==SMS_TIME_OUT.getCode()){
                    QuerySendDetailsRequest queryReq = new QuerySendDetailsRequest()
                        .setPhoneNumber(com.aliyun.teautil.Common.assertAsString(configurationDTO.getContacts().get(i).getPhoneNumber()))
                        .setBizId(bizId)
                        .setSendDate(LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE))
                        .setPageSize(10L)
                        .setCurrentPage(1L);
                //如果状态为空或者为超时，则查询
                    QuerySendDetailsResponse queryResp = client.querySendDetails(queryReq);
                    for (QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO dto : queryResp.body.smsSendDetailDTOs.smsSendDetailDTO) {
                        if (com.aliyun.teautil.Common.equalString(dto.sendStatus.toString(), "3")) {
                            System.out.println(dto.phoneNum + " 发送成功，接收时间: " + dto.receiveDate + "");
                            message.setWarningStatus(SUCCESS.getCode());
                            successCount++;
                        } else if (com.aliyun.teautil.Common.equalString(dto.sendStatus.toString(), "2")) {
                            System.out.println(dto.phoneNum + " 发送失败");
                            System.out.println("失败原因: " + dto.errCode);
                            message.setWarningStatus(FAILURE.getCode());
                            if(dto.errCode.equals("PORT_NOT_REGISTERED")){
                                message.setWarningStatus(SMS_PORT_NOT_REGISTERED.getCode());
                            }
                            successCount++;
                        } else {
                            System.out.println(dto.phoneNum + " 正在发送中...");
                            message.setWarningStatus(SMS_TIME_OUT.getCode());
                        }
                    }
                }
            }
        }
        //保存告警信息
        messageService.saveBatch(list);
    }



    @Override
    public void sendDing(ConfigurationDTO configurationDTO) {

    }

    @Override
    public void sendEmail(ConfigurationDTO configurationDTO) throws Exception {
        List<SysDictData> dictList = sysDictDataMapper.selectDictDataByType("email_setting")   ;
        Map<String, String> resultMap = dictList.stream()
                .collect(Collectors.toMap(
                        item -> item.getDictLabel(),
                        item -> item.getDictValue()
                ));
        //	账号信息
        String username = resultMap.get("usename");//	邮箱发送账号
        String password = resultMap.get("password");//	邮箱授权码，从具体的邮箱平台获取
        System.out.println("username:"+username);
        System.out.println("password:"+password);
        //	创建一个配置文件，并保存
        Properties props = new Properties();

        //	SMTP服务器连接信息
        //  126——smtp.126.com
        //  163——smtp.163.com
        props.put("mail.smtp.host", "smtp.163.com");//	SMTP主机名

        //  126——25
        //  163——465
        props.put("mail.smtp.port", "25");//	主机端口号
        props.put("mail.smtp.auth", "true");//	是否需要用户认证
        props.put("mail.smtp.starttls.enale", "true");//	启用TlS加密

        //	创建session会话
        //	参数1:smtp服务器连接参数
        //	参数2:账号和密码的授权认证对象
        Session session = Session.getInstance(props,new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);
            }
        });
        System.out.println(session);

        //构造邮件主体
        MimeMessage message = new MimeMessage(session);
        message.setSubject("甬昇运维报警");
        message.setText(configurationDTO.getDeviceName()+" 告警:"+configurationDTO.getTitle());
        message.setFrom(new InternetAddress("13867710176@163.com"));
        //message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("2439329113@qq.com"));
        // 将多个收件人邮箱地址转换为 Address 数组
        Address[] addresses = new Address[configurationDTO.getContacts().size()];
        List<Message> list = new java.util.ArrayList<>();
        Contacts contacts;
        for (int i = 0; i < configurationDTO.getContacts().size(); i++) {
            Message messages = new Message();
            contacts = configurationDTO.getContacts().get(i);
            if(ObjectUtils.isEmpty(contacts)||ObjectUtils.isEmpty(contacts.getEmail())){
                messages.setWarningStatus(EMAIL_ADDRESS_NULL.getCode());
            }else {
                addresses[i] = new InternetAddress(contacts.getEmail());
            }
            messages.setDeviceName(configurationDTO.getDeviceName());
            messages.setAreaId(configurationDTO.getAreaId());
            messages.setAreaName(configurationDTO.getAreaName());
            messages.setWarningType(configurationDTO.getWarningType());
            messages.setWarningWay(2);
            messages.setWarningLevel(configurationDTO.getWarningLevel());
            messages.setWarningContact(contacts.getContactsName());
            messages.setWarningContent(configurationDTO.getDeviceName()+" 告警:"+configurationDTO.getTitle());
            messages.setEventId(configurationDTO.getEventId());
            messages.setEventDetailId(configurationDTO.getEventDetailId());
            list.add(messages);
        }
        // 设置多个收件人
        message.setRecipients(MimeMessage.RecipientType.TO, addresses);

        //发送
        Transport.send(message);

        //保存告警信息
        messageService.saveBatch(list);

    }

    @Override
    //语音发送服务
    public void sendPhoneByVoice(ConfigurationDTO configurationDTO) throws Exception {
        List<SysDictData> dictList = sysDictDataMapper.selectDictDataByType("voice_setting");
        Map<String, String> resultMap = dictList.stream()
                .collect(Collectors.toMap(
                        item -> item.getDictLabel(),
                        item -> item.getDictValue()
                ));
        // 创建阿里云语音通话客户端
        com.aliyun.dyvmsapi20170525.Client client = phoneCreateClient();
        // 获取当前时间的Long格式，用于后续查询通话结果
        long currentTimeInMillis = System.currentTimeMillis();
        // 获取电话号码数组
        String[] phoneArray = configurationDTO.getContacts().stream()
                .map(Contacts::getPhoneNumber)
                .toArray(String[]::new);
//        Object[] phones = configurationDTO.getPhones().toArray();
        // 获取联系人数组
        String[] contacts = configurationDTO.getWarningContacts().split(",");
        // 初始化通话成功标志为false
        boolean isSuccess = false;

        // 如果电话号码数组不为空
        if (phoneArray.length > 0) {
            // 遍历电话号码数组
            for (int i = 0; i < phoneArray.length; i++) {
                // 初始化通话次数为1
                int callTimes = 1;
                // 循环拨打三次
                do {
                    // 创建语音通话请求对象
                    SingleCallByVoiceRequest req = new SingleCallByVoiceRequest()
                            // 设置被叫显示号码
                            .setCalledShowNumber(resultMap.get("showNumber"))
                            // 设置被叫号码
                            .setCalledNumber(phoneArray[i])
                            // 设置语音文件编码
                            .setVoiceCode(resultMap.get("voiceCode"))
                            // 设置播放次数
                            .setPlayTimes(Integer.valueOf(resultMap.get("playTimes")));
                    // 发送语音通话请求并获取响应
                    SingleCallByVoiceResponse resp = client.singleCallByVoice(req);
                    // 打印通话ID
                    System.out.println(resp.body.callId);

                    // 如果返回的不是OK，抛出异常
                    if (!com.aliyun.teautil.Common.equalString(resp.body.code, "OK")) {
                        throw new TeaException(TeaConverter.buildMap(
                                new TeaPair("code", resp.body.code),
                                new TeaPair("message", resp.body.message)
                        ));
                    }

                    // 等待一分钟后查询通话结果
                    Thread.sleep(60000);

                    // 创建查询通话详情请求对象
                    QueryCallDetailByCallIdRequest cReq = new QueryCallDetailByCallIdRequest()
                            // 设置通话ID
                            .setCallId(resp.body.callId)
                            // 设置产品ID
                            .setProdId(11000000300006L)
                            // 设置查询时间
                            .setQueryDate(currentTimeInMillis);

                    // 查询通话详情并获取响应
                    QueryCallDetailByCallIdResponse cResp = client.queryCallDetailByCallId(cReq);
                    // 打印通话详情
                    System.out.println(com.aliyun.teautil.Common.toJSONString(com.aliyun.teautil.Common.toMap(cResp)));

                    // 将通话详情转换为Map
                    Map<String, Object> map = JSON.parseObject(cResp.body.data, Map.class);
                    //保存告警信息
                    Message message = new Message();
                    message.setDeviceName(configurationDTO.getDeviceName());
                    message.setAreaId(configurationDTO.getAreaId());
                    message.setAreaName(configurationDTO.getAreaName());
                    message.setWarningType(configurationDTO.getWarningType());
                    message.setWarningWay(0);
                    message.setWarningLevel(configurationDTO.getWarningLevel());
                    message.setWarningContact(contacts[i]);
                    message.setWarningContent(configurationDTO.getDeviceName()+" 告警："+configurationDTO.getTitle());
                    message.setEventId(configurationDTO.getEventId());
                    // 如果通话时长为0，表示未接通
                    if (map.get("duration").equals(0)) {
                        System.out.println("未接通");
                        callTimes++;
                        message.setWarningStatus(PHONE_NOT_CONNECTED.getCode());
                        messageService.save(message);
                    } else {
                        System.out.println("接通");
                        isSuccess = true;
                        message.setWarningStatus(1);
                        messageService.save(message);
                        break;
                    }
                } while (callTimes <= 3);

                // 如果通话成功，打印联系人通话成功信息并跳出循环
                if (isSuccess) {
                    System.out.println(contacts[i] + "通话成功");
                    break;
                } else {
                    // 如果通话失败，打印联系人通话失败信息
                    System.out.println(contacts[i] + "通话失败");
                }
            }
        }
    }

    @Override
    public void sendPhoneByTts(ConfigurationDTO configurationDTO) throws Exception {
        List<SysDictData> dictList = sysDictDataMapper.selectDictDataByType("voice_setting");
        Map<String, String> resultMap = dictList.stream()
                .collect(Collectors.toMap(
                        item -> item.getDictLabel(),
                        item -> item.getDictValue()
                ));
        // 创建阿里云语音通话客户端
        com.aliyun.dyvmsapi20170525.Client client = phoneCreateClient();
        // 获取当前时间的Long格式，用于后续查询通话结果
        long currentTimeInMillis = System.currentTimeMillis();
        // 获取电话号码数组
        String[] phoneArray = configurationDTO.getContacts().stream()
                .map(Contacts::getPhoneNumber)
                .toArray(String[]::new);
//        Object[] phones = configurationDTO.getPhones().toArray();
        // 获取联系人数组
        String[] contacts = configurationDTO.getWarningContacts().split(",");
        // 初始化通话成功标志为false
        boolean isSuccess = false;

        // 如果电话号码数组不为空
        if (phoneArray.length > 0) {
            // 遍历电话号码数组
            for (int i = 0; i < phoneArray.length; i++) {
                // 初始化通话次数为1
                int callTimes = 1;
                // 循环拨打三次
                do {
                    SingleCallByTtsRequest ttsRequest = new SingleCallByTtsRequest()
                            // 设置被叫显示号码
                            .setCalledShowNumber(resultMap.get("showNumber"))
                            // 设置被叫号码
                            .setCalledNumber(phoneArray[i])
                            // 设置播放次数
                            .setPlayTimes(Integer.valueOf(resultMap.get("playTimes")))
                            // 设置文本转语音参数
                            .setTtsCode(resultMap.get("ttsCode"))
                            .setTtsParam("{\"device\":\""+configurationDTO.getDeviceName()+"\"}")
//                            .setTtsParam("{\"device\":\""+configurationDTO.getDeviceName()+
//                                    "\",\"title\":\""+configurationDTO.getTitle()+"\"}")
                            ;
                    // 发送语音通话请求并获取响应
                    SingleCallByTtsResponse resp = client.singleCallByTts(ttsRequest);
                    // 打印通话ID
                    System.out.println(resp.body.callId);

                    // 如果返回的不是OK，抛出异常
                    if (!com.aliyun.teautil.Common.equalString(resp.body.code, "OK")) {
                        throw new TeaException(TeaConverter.buildMap(
                                new TeaPair("code", resp.body.code),
                                new TeaPair("message", resp.body.message)
                        ));
                    }

                    // 等待一分钟后查询通话结果
                    Thread.sleep(60000);

                    // 创建查询通话详情请求对象
                    QueryCallDetailByCallIdRequest cReq = new QueryCallDetailByCallIdRequest()
                            // 设置通话ID
                            .setCallId(resp.body.callId)
                            // 设置产品ID
                            .setProdId(11000000300006L)
                            // 设置查询时间
                            .setQueryDate(currentTimeInMillis);

                    // 查询通话详情并获取响应
                    QueryCallDetailByCallIdResponse cResp = client.queryCallDetailByCallId(cReq);
                    // 打印通话详情
                    System.out.println(com.aliyun.teautil.Common.toJSONString(com.aliyun.teautil.Common.toMap(cResp)));

                    // 将通话详情转换为Map
                    Map<String, Object> map = JSON.parseObject(cResp.body.data, Map.class);
                    //保存告警信息
                    Message message = new Message();
                    message.setDeviceName(configurationDTO.getDeviceName());
                    message.setAreaId(configurationDTO.getAreaId());
                    message.setAreaName(configurationDTO.getAreaName());
                    message.setWarningType(configurationDTO.getWarningType());
                    message.setWarningWay(0);
                    message.setWarningLevel(configurationDTO.getWarningLevel());
                    message.setWarningContact(contacts[i]);
                    message.setWarningContent(configurationDTO.getDeviceName()+" 告警："+configurationDTO.getTitle());
                    message.setEventId(configurationDTO.getEventId());
                    message.setEventDetailId(configurationDTO.getEventDetailId());
                    // 如果通话时长为0，表示未接通
                    if (map.get("duration").equals(0)) {
                        System.out.println("未接通");
                        callTimes++;
                        message.setWarningStatus(PHONE_NOT_CONNECTED.getCode());
                        messageService.save(message);
                    } else {
                        System.out.println("接通");
                        isSuccess = true;
                        message.setWarningStatus(1);
                        messageService.save(message);
                        break;
                    }
                } while (callTimes <= 3);

                // 如果通话成功，打印联系人通话成功信息并跳出循环
                if (isSuccess) {
                    System.out.println(contacts[i] + "通话成功");
                    break;
                } else {
                    // 如果通话失败，打印联系人通话失败信息
                    System.out.println(contacts[i] + "通话失败");

                }
            }
        }
    }

    public static void sms(String[] args) throws Exception {
        // 获取电话号码数组
        com.aliyun.dysmsapi20170525.Client client = smsCreateClient();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers("13867710176")
                .setSignName("浙江时代短信提醒")
                .setTemplateCode("SMS_483235570")
                .setTemplateParam("{\"device\":\""+"测试用"+"\",\"title\":\""+"测试报警"+"\"}");
        // 1.发送短信
        SendSmsResponse sendResp = client.sendSms (sendSmsRequest);
        if (!com.aliyun.teautil.Common.equalString(sendResp.body.code, "OK")) {
            System.out.println("错误信息: " + sendResp.body.message + "");
            return ;
        }
        String bizId = sendResp.body.bizId;
        // 2. 等待 20 秒后查询结果
        Integer maxRetries = 3;//最大查询次数
        Integer sleepTime = 20000;//每次查询间隔时间
        List<Message> list = new java.util.ArrayList<>();
        for(int r = 0;r<maxRetries;r++){
            com.aliyun.teautil.Common.sleep(sleepTime);
            Message message = new Message();
            // 3.查询结果
            if(ObjectUtils.isEmpty(message.getWarningStatus())||message.getWarningStatus()==SMS_TIME_OUT.getCode()){
                QuerySendDetailsRequest queryReq = new QuerySendDetailsRequest()
                        .setPhoneNumber("13867710176")
                        .setBizId(bizId)
                        .setSendDate(LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE))
                        .setPageSize(10L)
                        .setCurrentPage(1L);
                //如果状态为空或者为超时，则查询
                QuerySendDetailsResponse queryResp = client.querySendDetails(queryReq);
                for (QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO dto : queryResp.body.smsSendDetailDTOs.smsSendDetailDTO) {
                    if (com.aliyun.teautil.Common.equalString(dto.sendStatus.toString(), "3")) {
                        System.out.println(dto.phoneNum + " 发送成功，接收时间: " + dto.receiveDate + "");
                        message.setWarningStatus(SUCCESS.getCode());
                    } else if (com.aliyun.teautil.Common.equalString(dto.sendStatus.toString(), "2")) {
                        System.out.println(dto.phoneNum + " 发送失败");
                        System.out.println("失败原因: " + dto.errCode);
                        message.setWarningStatus(FAILURE.getCode());
                        if(dto.errCode.equals("PORT_NOT_REGISTERED")){
                            message.setWarningStatus(SMS_PORT_NOT_REGISTERED.getCode());
                        }
                    } else {
                        System.out.println(dto.phoneNum + " 正在发送中...");
                        message.setWarningStatus(SMS_TIME_OUT.getCode());
                    }
                }
            }

        }
    }

    public static void main(String[] args) throws Exception {
        // 创建阿里云语音通话客户端
        com.aliyun.dyvmsapi20170525.Client client = phoneCreateClient();
        // 获取当前时间的Long格式，用于后续查询通话结果
        long currentTimeInMillis = System.currentTimeMillis();

        // 初始化通话成功标志为false
        boolean isSuccess = false;

        // 初始化通话次数为1
        int callTimes = 1;
        // 循环拨打三次
        do {
            SingleCallByTtsRequest ttsRequest = new SingleCallByTtsRequest()
                    // 设置被叫显示号码
                    .setCalledShowNumber("051880142566")
                    // 设置被叫号码
                    .setCalledNumber("13867710176")
                    // 设置播放次数
                    .setPlayTimes(1)
                    // 设置文本转语音参数
                    .setTtsCode("TTS_315260121")
                    .setTtsParam("{\"device\":\""+"测试设备"+"\"}")
                    ;
            // 发送语音通话请求并获取响应
            SingleCallByTtsResponse resp = client.singleCallByTts(ttsRequest);
            // 打印通话ID
            System.out.println(resp.body.callId);

            // 如果返回的不是OK，抛出异常
            if (!com.aliyun.teautil.Common.equalString(resp.body.code, "OK")) {
                throw new TeaException(TeaConverter.buildMap(
                        new TeaPair("code", resp.body.code),
                        new TeaPair("message", resp.body.message)
                ));
            }

            // 等待一分钟后查询通话结果
            Thread.sleep(60000);

            // 创建查询通话详情请求对象
            QueryCallDetailByCallIdRequest cReq = new QueryCallDetailByCallIdRequest()
                    // 设置通话ID
                    .setCallId(resp.body.callId)
                    // 设置产品ID
                    .setProdId(11000000300006L)
                    // 设置查询时间
                    .setQueryDate(currentTimeInMillis);

            // 查询通话详情并获取响应
            QueryCallDetailByCallIdResponse cResp = client.queryCallDetailByCallId(cReq);
            // 打印通话详情
            System.out.println(com.aliyun.teautil.Common.toJSONString(com.aliyun.teautil.Common.toMap(cResp)));

            // 将通话详情转换为Map
            Map<String, Object> map = JSON.parseObject(cResp.body.data, Map.class);

            // 如果通话时长为0，表示未接通
            if (map.get("duration").equals(0)) {
                System.out.println("未接通");
                callTimes++;
            } else {
                System.out.println("接通");
                break;
            }
        } while (callTimes <= 3);

        // 如果通话成功，打印联系人通话成功信息并跳出循环
        if (isSuccess) {
            System.out.println("通话成功");

        } else {
            // 如果通话失败，打印联系人通话失败信息
            System.out.println("通话失败");

        }
    }

    @Override
    public String disposeSms(Contacts contacts, Event event) throws Exception {
        List<SysDictData> dictList = sysDictDataMapper.selectDictDataByType("sms_setting")   ;
        Map<String, String> resultMap = dictList.stream()
                .collect(Collectors.toMap(
                        item -> item.getDictLabel(),
                        item -> item.getDictValue()
                ));
        com.aliyun.dysmsapi20170525.Client client = smsCreateClient();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(contacts.getPhoneNumber())
                .setSignName(resultMap.get("signName"))
                .setTemplateCode("SMS_486575113")
                .setTemplateParam("{\"host\":\""+"设备"+event.getHostName()+"\"}");
        // 1.发送短信
        SendSmsResponse sendResp = client.sendSms (sendSmsRequest);
        if (!com.aliyun.teautil.Common.equalString(sendResp.body.code, "OK")) {
            System.out.println("错误信息: " + sendResp.body.message + "");
            return sendResp.body.message;
        }
        String bizId = sendResp.body.bizId;
        // 2. 等待 20 秒后查询结果
        Integer maxRetries = 3;//最大查询次数
        Integer sleepTime = 20000;//每次查询间隔时间
        List<Message> list = new java.util.ArrayList<>();
        Integer successCount = 0;
        for(int r = 0;r<maxRetries;r++){
            com.aliyun.teautil.Common.sleep(sleepTime);
            // 3.查询结果
            QuerySendDetailsRequest queryReq = new QuerySendDetailsRequest()
                    .setPhoneNumber(com.aliyun.teautil.Common.assertAsString(contacts.getPhoneNumber()))
                    .setBizId(bizId)
                    .setSendDate(LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE))
                    .setPageSize(10L)
                    .setCurrentPage(1L);
            //如果状态为空或者为超时，则查询
            QuerySendDetailsResponse queryResp = client.querySendDetails(queryReq);
            for (QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO dto : queryResp.body.smsSendDetailDTOs.smsSendDetailDTO) {
                if (com.aliyun.teautil.Common.equalString(dto.sendStatus.toString(), "3")) {
                    System.out.println(dto.phoneNum + " 发送成功，接收时间: " + dto.receiveDate + "");
                    successCount++;
                    return SUCCESS.getMessage();
                } else if (com.aliyun.teautil.Common.equalString(dto.sendStatus.toString(), "2")) {
                    System.out.println(dto.phoneNum + " 发送失败");
                    System.out.println("失败原因: " + dto.errCode);
                    successCount++;
                    if(dto.errCode.equals("PORT_NOT_REGISTERED")){
                        return SMS_PORT_NOT_REGISTERED.getMessage();
                    }
                    return FAILURE.getMessage();
                } else {
                    System.out.println(dto.phoneNum + " 正在发送中...");
                    return SMS_TIME_OUT.getMessage();
                }
            }
        }
        return "推送成功";
    }

    public static com.aliyun.dysmsapi20170525.Client smsCreateClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
//                .setAccessKeyId(System.getenv("LTAI5tsCYhQQkc9ZENgZZCmN"))
                .setAccessKeyId("LTAI5tSCYhQQkc9ZENqZZCmN")
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret("dofzFpD7UggasldepW81ei2q9YNgS5");
//                .setAccessKeySecret(System.getenv("dofzFpD7Uggasldepw81ei2q9YNgS5"));
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static com.aliyun.dyvmsapi20170525.Client phoneCreateClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI5tSCYhQQkc9ZENqZZCmN")
                .setAccessKeySecret("dofzFpD7UggasldepW81ei2q9YNgS5");
        return new com.aliyun.dyvmsapi20170525.Client(config);
    }

}
